package com.homelink.android.explorerup.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.homelink.android.explorerup.R;
import com.homelink.android.explorerup.component.FileDetails;
import com.homelink.android.explorerup.component.ObtainFilePropertiesTask;
import com.homelink.android.explorerup.view.NumOfImageView;
import com.homelink.android.explorerup.view.NumOfImageView.SelectMode;

/**
 * 
 * @author hliang@126.com
 * 
 */
public class SimpleFileListAdapter extends BaseFileListAdapter implements
		ObtainFilePropertiesTask.OnObtainFilePropertiesListener {
	public static final String TAG = "SimpleFileListAdapter";
	private Context mContext;
	private LayoutInflater mInflater;

	public SimpleFileListAdapter(Context ctx) {
		mContext = ctx;
		mInflater = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View v = null;
		ViewHolder holder = null;
		if (convertView == null) {
			v = mInflater.inflate(R.layout.fileitem, null);
			holder = new ViewHolder();
			holder.iconImage = (NumOfImageView) v.findViewById(R.id.fileIcon);
			holder.nameView = (TextView) v.findViewById(R.id.fileName);

			v.setTag(holder);
		} else {
			v = (View) convertView;
			holder = (ViewHolder) v.getTag();
			holder.reset();
		}

		FileDetails fileDetails = (FileDetails) getItem(position);
		holder.nameTxt = fileDetails.name;
		holder.nameView.setText(holder.nameTxt);
		holder.itemIndex = position;

		if (isSelectEnable()) {
			Log.d(TAG, "getView position: " + position + " selected: "
					+ getSelected(position));
			holder.iconImage
					.setSelectMode(getSelected(position) ? SelectMode.SELECTED
							: SelectMode.UNSELECTED);
		} else {
			holder.iconImage.setSelectMode(SelectMode.NORMAL);
		}

		View.OnClickListener l = getItemClickListener();
		if (l != null) {
			v.setOnClickListener(l);
		}

		View.OnTouchListener tl = getItemTouchListener();
		if (tl != null) {
			v.setOnTouchListener(tl);
		}
		View.OnLongClickListener tll = getItemOnLongClickListener();
		if (tll != null) {
			v.setOnLongClickListener(tll);
		}

		ObtainFilePropertiesTask task = new ObtainFilePropertiesTask(
				getBasePath());
		task.setListener(this);
		task.execute(holder);
		// Log.d(TAG,"getView():  "+ holder.nameTxt);
		return v;
	}

	@Override
	public Types getType() {
		return Types.Simple;
	}

	public void onObtainFinished(BaseFileListAdapter.ViewHolder holder) {
		// this.notifyDataSetChanged();
		holder.iconImage.invalidate();
		holder.nameView.invalidate();
	}

}
